import * as actions from './';
import HttpRequest from './../common/http';

const rootUrl = window.restConfig.rootUrl;

export const saveName = (name, callback) => {
  return (dispatch) => {
    HttpRequest.post(rootUrl + '/ensure/account')
      .then((ret) => {
        if (ret.code === 10000) {  // 发送验证码成功与否 应该不弹出东西??
          dispatch({
            type: actions.APPOINT_STEP_CHANGE,
            data: {
              state: ret.data || {}
            }
          });
          callback();
        }
      }).catch((err) => {
        dispatch(showError(err.message));
      });
  }
}

export const getContacts = (id, period, callback) => {
  return (dispatch) => {
    HttpRequest.post(rootUrl + '/appointment/contacts', {
      customerId: 'd957c570c9ae11e7a7727f8890368983',
      periodId: 'ee392901c9b011e7beec814c199c23bc'
    })
      .then((ret) => {
        if (ret.code === 10000) {
          dispatch({
            type: actions.APPOINT_CHANGE,
            data: {
              state: {
                contacts: ret.data
              }
            }
          });
          callback();
        }
      }).catch((err) => {
        dispatch(showError(err.message));
      });
  }
}

export const submitAppoint = (periodId, callback) => {
  return (dispatch, getState) => {
    let state = getState().appointSteps || {}
    // HttpRequest.post(rootUrl + '/appointment/appoint', {
    //   periodId: periodId,
    //   ...state.data
    // })
     HttpRequest.post(rootUrl + '/appointment/appoint', {
      customerId: "d957c570c9ae11e7a7727f8890368983",
      periodId: "ee392901c9b011e7beec814c199c23bc",
      persons: [
        "bb2bd040c9af11e7a7727f8890368983"
      ]
    })
      .then((ret) => {
        if (ret.code === 10000) {  
          callback();
        }
      }).catch((err) => {
        dispatch(showError(err.message));
      });
  }
}

export const dataChange = (name, value) => {
  return {
    type: actions.APPOINT_STEP_CHANGE,
    data: {
      data: {
        [name]: value
      }
    }
  }
}

export const errorChange = (name, value) => {
  return {
    type: actions.APPOINT_STEP_CHANGE,
    data: {
      error: {
        [name]: value
      }
    }
  }
}

export const showError = (text) => {
  return (dispatch) => {
    dispatch(errorChange('hasError', true));
    dispatch(errorChange('msg', text));

    let timer = setTimeout( () => {
      window.clearTimeout(timer);
      dispatch(errorChange('hasError', false));
      dispatch(errorChange('msg', ''));
    }, 2000);
  }
}